package com.sxbbc.common.core.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.sxbbc.common.basics.utils.date.DateUtil;
import com.sxbbc.common.core.dto.jz.FreezeDTO;
import com.sxbbc.common.core.dto.jz.FreezeVo;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.FreezeStatusEnums;
import com.sxbbc.common.core.enums.HandleTypeEnums;
import com.sxbbc.common.core.mapper.jz.*;
import com.sxbbc.common.core.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;

/**
 * 账户变动操作 业务层实现
 *
 * @author xiaoky
 * @date 2019-06-03
 */
@SuppressWarnings("all")
@Service
public class AccountChangeServiceImpl implements IAccountChangeService {

    private static Logger logger = LogManager.getLogger(AccountChangeServiceImpl.class);

    @Autowired
    private CAccountMapper cAccountMapper;
    @Autowired
    private CPointDetailMapper cPointDetailMapper;
    @Autowired
    private BRedMoneyDetailMapper bRedMoneyDetailMapper;
    @Autowired
    private CRedMoneyDetailMapper cRedMoneyDetailMapper;
    @Autowired
    private CMoneyDetailMapper cMoneyDetailsMapper;
    @Autowired
    private SysDealDetailMapper sysDealDetailMapper;
    @Autowired
    private ICMoneyDetailService cMoneyDetailService;
    @Autowired
    private ICPointDetailService cPointDetailService;
    @Autowired
    private ICDonateDetailService cDonateDetailService;
    @Autowired
    private ICShareDetailService cShareDetailService;
    @Autowired
    private BAccountMapper bAccountMapper;
    @Autowired
    private IBMoneyDetailService bMoneyDetailService;
    @Autowired
    private IBPointDetailService bPointDetailService;
    @Autowired
    private IAgDonateDetailService agDonateDetailService;
    @Autowired
    private IAgAccountService agAccountService;
    @Autowired
    private ICAccountService icAccountService;
    @Autowired
    private IBAccountService ibAccountService;
    @Autowired
    private ICFreezePointDetailService icFreezePointDetailService;
    @Autowired
    private ICFreezeDonateDetailService icFreezeDonateDetailService;
    @Autowired
    private IBFreezeMoneyDetailService ibFreezeMoneyDetailService;
    @Autowired
    private ISysDealDataService sysDealDataService;
    @Autowired
    private ISysDealDetailService sysDealDetailService;
    @Autowired
    private IInfoParamService infoParamService;
    @Autowired
    private BBusinessService bBusinessService;
    @Autowired
    ICFreezeMoneyDetailService icFreezeMoneyDetailService;
    @Autowired
    private AgAccountMapper agAccountMapper;
    @Autowired
    private IAgAccountService iAgAccountService;
    @Autowired
    private IAgMoneyDetailService iAgMoneyDetailService;
    @Autowired
    private IAgShareDetailService iAgShareDetailService;
    @Autowired
    private IAgFreezeDonateDetailService iAgFreezeDonateDetailService;
    @Autowired
    private IAgFreezeMoneyDetailService iAgFreezeMoneyDetailService;

    @Override
    public boolean checkHandleAccount() {
        //暂时不能通过后台动态设置开关时间段
        long l = DateUtil.getInstance().getTime(new Date());
        if (ACCOUNT_CLOSE_START < l && l < ACCOUNT_CLOSE_END) {
            return false;
        }
        return true;
    }

    @Override
    public String insertCMoneyDetail(Integer cid, Integer typeId, Integer isOut, String payCode, BigDecimal cost,
                                     String remark, Integer targetId) {
        String result = "";
        try {
            //行锁数据
            CAccount account = cAccountMapper.getByCid(cid);
            BigDecimal originalMoney = account.getMoney();
            BigDecimal money = account.getMoney();
            CalcuUtils cal = CalcuUtils.getInstance();
            if (cal.isEquals(StaticUtils.PAY_IN, isOut)) {
                money = cal.add(money, cost, 2);
            } else {
                money = cal.sub(money, cost, 2);
            }
            if (money.compareTo(BigDecimal.ZERO) < 0) {
                return "余额不足";
            }
            account.setMoney(money);
            //首先修改余额  根据当前版本号去修改
            int i = cAccountMapper.updateLockVersion(account);
            if (i < 1) {
                return "重复提交数据";
            }
            CMoneyDetail detail = new CMoneyDetail();
            detail.setCid(cid);
            detail.setTypeId(typeId);
            detail.setPayCode(payCode);
            detail.setIsout(isOut);
            detail.setOriginal(originalMoney);
            detail.setCost(cost);
            detail.setLast(money);
            detail.setRemark(remark);
            detail.setTargetid(targetId);
            cMoneyDetailService.save(detail);
        } catch (Exception e) {
            logger.info("操作用户余额明细异常：" + e.getMessage());
            throw new ThrowJsonException("保存校验用户余额异常");
        }
        return result;
    }

    @Override
    public String insertCPointDetail(Integer cid, Integer typeId, Integer isOut, String payCode, BigDecimal cost,
                                     String remark, Integer targetId) {
        String result = "";
        try {
            //行锁数据
            CAccount account = cAccountMapper.getByCid(cid);
            BigDecimal originalPoint = account.getPoint();
            BigDecimal point = account.getPoint();
            CalcuUtils cal = CalcuUtils.getInstance();
            if (cal.isEquals(StaticUtils.PAY_IN, isOut)) {
                point = cal.add(point, cost, 2);
            } else {
                point = cal.sub(point, cost, 2);
            }
            if (point.compareTo(BigDecimal.ZERO) < 0) {
                return "积分不足";
            }
            account.setPoint(point);
            //首先修改余额  根据当前版本号去修改
            int i = cAccountMapper.updateLockVersion(account);
            if (i < 1) {
                return "重复提交数据";
            }
            CPointDetail detail = new CPointDetail();
            detail.setCid(cid);
            detail.setTypeId(typeId);
            detail.setPayCode(payCode);
            detail.setIsout(isOut);
            detail.setOriginal(originalPoint);
            detail.setCost(cost);
            detail.setLast(point);
            detail.setRemark(remark);
            detail.setTargetid(targetId);
            cPointDetailService.save(detail);
        } catch (Exception e) {
            logger.info("操作用户积分明细异常：" + e.getMessage());
            throw new ThrowJsonException("保存校验用户积分异常");
        }
        return result;
    }

    @Override
    public String insertBMoneyDetail(Integer bid, Integer typeId, Integer isOut, String payCode, BigDecimal cost,
                                     String remark, Integer targetId) {
        String result = "";
        try {
            //行锁数据
            BAccount account = bAccountMapper.getByBid(bid);
            BigDecimal originalMoney = account.getMoney();
            BigDecimal money = account.getMoney();
            CalcuUtils cal = CalcuUtils.getInstance();
            if (cal.isEquals(StaticUtils.PAY_IN, isOut)) {
                money = cal.add(money, cost, 2);
            } else {
                money = cal.sub(money, cost, 2);
            }
            if (money.compareTo(BigDecimal.ZERO) < 0) {
                return "余额不足";
            }
            account.setMoney(money);
            //首先修改余额  根据当前版本号去修改
            int i = bAccountMapper.updateLockVersion(account);
            if (i < 1) {
                return "重复提交数据";
            }
            BMoneyDetail detail = new BMoneyDetail();
            detail.setBid(bid);
            detail.setTypeId(typeId);
            detail.setPayCode(payCode);
            detail.setIsout(isOut);
            detail.setOriginal(originalMoney);
            detail.setCost(cost);
            detail.setLast(money);
            detail.setRemark(remark);
            detail.setTargetId(targetId);
            bMoneyDetailService.save(detail);
        } catch (Exception e) {
            logger.info("操作店铺余额明细异常：" + e.getMessage());
            throw new ThrowJsonException("保存校验店铺余额异常");
        }
        return result;
    }

    @Override
    public String insertAgMoneyDetail(Integer agid, Integer typeId, Integer isout, String payCode, BigDecimal cost,
                                      String remark, Integer targetId) {
        String result = "";
        try {
            //行锁数据
            AgAccount account = agAccountMapper.getById(agid);
            BigDecimal originalMoney = account.getMoney();
            BigDecimal money = account.getMoney();
            CalcuUtils cal = CalcuUtils.getInstance();
            if (cal.isEquals(StaticUtils.PAY_IN, isout)) {
                money = cal.add(money, cost, 2);
            } else {
                money = cal.sub(money, cost, 2);
            }
            if (money.compareTo(BigDecimal.ZERO) < 0) {
                return "余额不足";
            }
            account.setMoney(money);
            //首先修改余额  根据当前版本号去修改
            int i = agAccountMapper.updateLockVersion(account);
            if (i < 1) {
                return "重复提交数据";
            }
            AgMoneyDetail detail = new AgMoneyDetail();
            detail.setAgid(agid);
            detail.setTypeId(typeId);
            detail.setPayCode(payCode);
            detail.setIsout(isout);
            detail.setOriginal(originalMoney);
            detail.setCost(cost);
            detail.setLast(money);
            detail.setRemark(remark);
            detail.setTargetId(targetId);
            iAgMoneyDetailService.save(detail);
        } catch (Exception e) {
            logger.info("操作代理余额明细异常：" + e.getMessage());
            throw new ThrowJsonException("保存校验代理余额异常");
        }
        return result;
    }

    @Override
    public String handleFreezeReturn(FreezeVo freezeVo) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        boolean save = false;
        String remark = "";
        try {
            // 先将商家的冻结金额退还
            QueryWrapper<BFreezeMoneyDetail> bWrapper = new QueryWrapper<BFreezeMoneyDetail>();
            bWrapper.eq("order_detail_id", freezeVo.getOrderDetailId()).
                    eq("pay_code", freezeVo.getPayCode()).
                    eq("bid", freezeVo.getBid()).
                    eq("status", FreezeStatusEnums.FREEZING.getId()).
                    eq("type", freezeVo.getType());
            BFreezeMoneyDetail bFreezeMoney = ibFreezeMoneyDetailService.getOne(bWrapper);
            if (bFreezeMoney == null) {
                return "操作失败";
            }
            // 修改冻结状态
            bFreezeMoney.setStatus(FreezeStatusEnums.RETURN.getId());
            save = ibFreezeMoneyDetailService.updateById(bFreezeMoney);
            if (!save) {
                return "操作商家冻结数据异常";
            }
            //1.1 处理商家账户的冻结信息
            BAccount bAccount = ibAccountService.selectByBid(freezeVo.getBid());
            //1.2 原始冻结金额
            BigDecimal originalFreezeMoney = bAccount.getFreezeMoney();
            //1.3 最终冻结金额
            BigDecimal finallyFreezeMoney = calUtil.sub(originalFreezeMoney, bFreezeMoney.getMoney(), 2);
            bAccount.setFreezeMoney(finallyFreezeMoney);
            save = ibAccountService.updateByBid(bAccount);
            if (!save) {
                return "操作商家账户异常";
            }

//            // 再是用户的冻结积分
//            QueryWrapper<CFreezePointDetail> cWrapper = new QueryWrapper<CFreezePointDetail>();
//            cWrapper.eq("order_detail_id", freezeVo.getOrderDetailId()).eq("pay_code", freezeVo.getPayCode())
//                    .eq("cid", freezeVo.getCid()).eq("status", FreezeStatusEnums.FREEZING.getId()).eq("type", freezeVo.getType());
//            CFreezePointDetail cFreezePoint = icFreezePointDetailService.getOne(cWrapper);
//            if (cFreezePoint == null) {
//                return "操作失败";
//            }
//            // 修改冻结状态
//            cFreezePoint.setStatus(FreezeStatusEnums.RETURN.getId());
//            save = icFreezePointDetailService.updateById(cFreezePoint);
//            if (!save) {
//                return "操作用户冻结数据异常";
//            }
//            //2.1 处理用户账户的冻结信息
//            CAccount cAccount = icAccountService.selectByCid(freezeVo.getCid());
//            //2.2 原始冻结积分
//            BigDecimal originalFreezePoint = cAccount.getFreezePoint();
//            //2.3 最终冻结积分
//            BigDecimal finallyFreezePoint = calUtil.sub(originalFreezePoint, cFreezePoint.getPoint(), 2);
//            cAccount.setFreezePoint(finallyFreezePoint);
//            save = icAccountService.updateByCid(cAccount);
//            if (!save) {
//                return "操作用户账户异常";
//            }
        } catch (Exception e) {
            throw new ThrowJsonException("保存冻结记录异常");
        }
        return remark;
    }

    @Override
    public String handleFreezeCustomerMoney(FreezeDTO dto) {
        if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.FREEZING.getId())) {
            CAccount account = icAccountService.selectByCid(dto.getCid());
            BigDecimal freezeVal = account.getFreezeMoney();
            account.setFreezeMoney(CalcuUtils.getInstance().add(freezeVal, dto.getFreeze(), 2));
            boolean b = icAccountService.updateByCid(account);
            if (!b) {
                throw new ThrowJsonException("重复提交");
            }
            CFreezeMoneyDetail detail = new CFreezeMoneyDetail();
            BeanUtils.copyProperties(dto, detail);
            detail.setMoney(dto.getFreeze());
            if (StringUtils.isBlank(dto.getRemark())) {
                detail.setRemark(HandleTypeEnums.getName(dto.getTypeId()));
            } else {
                detail.setRemark(dto.getRemark());
            }
            if (!icFreezeMoneyDetailService.save(detail)) {
                throw new ThrowJsonException("保存用户冻结金额记录失败");
            }
        } else if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.SEND.getId())) {
            QueryWrapper<CFreezeMoneyDetail> queryWrapper = new QueryWrapper<CFreezeMoneyDetail>();
            if (CalcuUtils.getInstance().isEquals(dto.getGranularity(), 2)) {
                queryWrapper.eq("order_detail_id", dto.getOrderDetailId());
            } else {
                queryWrapper.eq("pay_code", dto.getPayCode());
            }
            List<CFreezeMoneyDetail> list = icFreezeMoneyDetailService.list(queryWrapper);
            for (CFreezeMoneyDetail d : list) {
                if (d.getStatus() != FreezeStatusEnums.FREEZING.getId()) {
                    continue;
                }
                CAccount account = icAccountService.selectByCid(d.getCid());
                BigDecimal freezeVal = account.getFreezeMoney();
                account.setFreezeMoney(CalcuUtils.getInstance().sub(freezeVal, d.getMoney(), 2));
                if (account.getFreezeMoney().compareTo(BigDecimal.ZERO) < 0) {
                    continue;
                }
                boolean b = icAccountService.updateByCid(account);
                if (!b) {
                    continue;//重复提交
                }
                d.setStatus(dto.getStatus());
                icFreezeMoneyDetailService.updateById(d);
                //增加账户对应值
                insertCMoneyDetail(d.getCid(), d.getTypeId(), StaticUtils.PAY_IN, d.getPayCode(), d.getMoney(), d.getRemark(), d.getTargetId());
            }
        } else if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.RETURN.getId())) {
            QueryWrapper<CFreezeMoneyDetail> queryWrapper = new QueryWrapper<CFreezeMoneyDetail>();
            queryWrapper.eq("order_detail_id", dto.getOrderDetailId());
            List<CFreezeMoneyDetail> list = icFreezeMoneyDetailService.list(queryWrapper);
            for (CFreezeMoneyDetail d : list) {
                if (!CalcuUtils.getInstance().isEquals(d.getStatus(), FreezeStatusEnums.FREEZING.getId())) {
                    continue;
                }
                CAccount account = icAccountService.selectByCid(d.getCid());
                BigDecimal freezeVal = account.getFreezeMoney();
                account.setFreezeMoney(CalcuUtils.getInstance().sub(freezeVal, d.getMoney(), 2));
                if (account.getFreezeMoney().compareTo(BigDecimal.ZERO) < 0) {
                    continue;
                }
                boolean b = icAccountService.updateByCid(account);
                if (!b) {
                    continue;//重复提交
                }
                d.setStatus(dto.getStatus());
                icFreezeMoneyDetailService.updateById(d);
            }
        }
        return "";
    }

    @Override
    public String handleFreezeCustomerPoint(FreezeDTO dto) {
        if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.FREEZING.getId())) {
            CAccount account = icAccountService.selectByCid(dto.getCid());
            BigDecimal freezeVal = account.getFreezePoint();
            account.setFreezePoint(CalcuUtils.getInstance().add(freezeVal, dto.getFreeze(), 2));
            boolean b = icAccountService.updateByCid(account);
            if (!b) {
                throw new ThrowJsonException("重复提交");
            }
            CFreezePointDetail detail = new CFreezePointDetail();
            BeanUtils.copyProperties(dto, detail);
            detail.setPoint(dto.getFreeze());
            detail.setRemark(HandleTypeEnums.getName(dto.getTypeId()));
            if (!icFreezePointDetailService.save(detail)) {
                throw new ThrowJsonException("保存用户冻结积分记录失败");
            }
        } else if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.SEND.getId())) {
            QueryWrapper<CFreezePointDetail> queryWrapper = new QueryWrapper<CFreezePointDetail>();
            //解冻粒度 批量和单个详情
            if (CalcuUtils.getInstance().isEquals(dto.getGranularity(), 2)) {
                queryWrapper.eq("order_detail_id", dto.getOrderDetailId());
            } else {
                queryWrapper.eq("pay_code", dto.getPayCode());
            }
            queryWrapper.eq("status", FreezeStatusEnums.FREEZING.getId());
            List<CFreezePointDetail> list = icFreezePointDetailService.list(queryWrapper);
            for (CFreezePointDetail d : list) {
                CAccount account = icAccountService.selectByCid(d.getCid());
                BigDecimal freezeVal = account.getFreezePoint();
                account.setFreezePoint(CalcuUtils.getInstance().sub(freezeVal, d.getPoint(), 2));
                if (account.getFreezePoint().compareTo(BigDecimal.ZERO) < 0) {
                    throw new ThrowJsonException("用户账户冻结积分不足");
                }
                boolean b = icAccountService.updateByCid(account);
                if (!b) {
                    throw new ThrowJsonException("用户账户重复提交");
                }
                d.setStatus(dto.getStatus());
                b = icFreezePointDetailService.updateById(d);
                if (!b) {
                    throw new ThrowJsonException("保存用户冻结积分记录失败");
                }
                //增加账户对应值
                String r = insertCPointDetail(d.getCid(), d.getTypeId(), StaticUtils.PAY_IN, d.getPayCode(), d.getPoint(), d.getRemark(), d.getTargetId());
                if (r.length() > 0) {
                    throw new ThrowJsonException("解冻失败：" + r);
                }
            }
        } else if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.RETURN.getId())) {
            QueryWrapper<CFreezePointDetail> queryWrapper = new QueryWrapper<CFreezePointDetail>();
            queryWrapper.eq("order_detail_id", dto.getOrderDetailId());
            queryWrapper.eq("status", FreezeStatusEnums.FREEZING.getId());
            List<CFreezePointDetail> list = icFreezePointDetailService.list(queryWrapper);
            for (CFreezePointDetail d : list) {
                CAccount account = icAccountService.selectByCid(d.getCid());
                BigDecimal freezeVal = account.getFreezePoint();
                account.setFreezePoint(CalcuUtils.getInstance().sub(freezeVal, d.getPoint(), 2));
                if (account.getFreezePoint().compareTo(BigDecimal.ZERO) < 0) {
                    throw new ThrowJsonException("用户账户冻结积分不足");
                }
                boolean b = icAccountService.updateByCid(account);
                if (!b) {
                    throw new ThrowJsonException("保存用户冻结积分记录失败");
                }
                d.setStatus(dto.getStatus());
                b = icFreezePointDetailService.updateById(d);
                if (!b) {
                    throw new ThrowJsonException("保存用户冻结积分记录失败");
                }
            }
        }
        return "";
    }

    @Override
    public String handleFreezeBusinessMoney(FreezeDTO dto) {
        if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.FREEZING.getId())) {
            BAccount account = ibAccountService.selectByBid(dto.getBid());
            BigDecimal freezeVal = account.getFreezeMoney();
            account.setFreezeMoney(CalcuUtils.getInstance().add(freezeVal, dto.getFreeze(), 2));
            boolean b = ibAccountService.updateByBid(account);
            if (!b) {
                throw new ThrowJsonException("商家冻结账户重复提交");
            }
            BFreezeMoneyDetail detail = new BFreezeMoneyDetail();
            BeanUtils.copyProperties(dto, detail);
            detail.setMoney(dto.getFreeze());
            detail.setRemark(HandleTypeEnums.getName(dto.getTypeId()));
            if (!ibFreezeMoneyDetailService.save(detail)) {
                throw new ThrowJsonException("保存商家冻结金额的冻结记录失败");
            }

        } else if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.SEND.getId())) {
            QueryWrapper<BFreezeMoneyDetail> queryWrapper = new QueryWrapper<BFreezeMoneyDetail>();
            //解冻粒度 批量和单个详情
            if (CalcuUtils.getInstance().isEquals(dto.getGranularity(), 2)) {
                queryWrapper.eq("order_detail_id", dto.getOrderDetailId());
            } else {
                queryWrapper.eq("pay_code", dto.getPayCode());
            }
            queryWrapper.eq("status", FreezeStatusEnums.FREEZING.getId());
            List<BFreezeMoneyDetail> list = ibFreezeMoneyDetailService.list(queryWrapper);
            for (BFreezeMoneyDetail d : list) {
                BAccount account = ibAccountService.selectByBid(d.getBid());
                BigDecimal freezeVal = account.getFreezeMoney();
                account.setFreezeMoney(CalcuUtils.getInstance().sub(freezeVal, d.getMoney(), 2));
                if (account.getFreezeMoney().compareTo(BigDecimal.ZERO) < 0) {
                    throw new ThrowJsonException("商家账户冻结金额不足");
                }
                boolean b = ibAccountService.updateByBid(account);
                if (!b) {
                    throw new ThrowJsonException("商家冻结账户重复提交");
                }
                d.setStatus(dto.getStatus());
                d.setUpdateTime(dto.getUpdateTime());
                b = ibFreezeMoneyDetailService.updateById(d);
                if (!b) {
                    throw new ThrowJsonException("保存商家冻结金额的解冻记录失败");
                }
                //增加账户对应值
                String r = insertBMoneyDetail(d.getBid(), d.getTypeId(), StaticUtils.PAY_IN, d.getPayCode(), d.getMoney(), d.getRemark(), d.getTargetId());
                if (r.length() > 0) {
                    throw new ThrowJsonException("解冻失败：" + r);
                }
            }
        } else if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.RETURN.getId())) {
            QueryWrapper<BFreezeMoneyDetail> queryWrapper = new QueryWrapper<BFreezeMoneyDetail>();
            queryWrapper.eq("order_detail_id", dto.getOrderDetailId());
            queryWrapper.eq("status", FreezeStatusEnums.FREEZING.getId());
            List<BFreezeMoneyDetail> list = ibFreezeMoneyDetailService.list(queryWrapper);
            for (BFreezeMoneyDetail d : list) {
                BAccount account = ibAccountService.selectByBid(d.getBid());
                BigDecimal freezeVal = account.getFreezeMoney();
                account.setFreezeMoney(CalcuUtils.getInstance().sub(freezeVal, d.getMoney(), 2));
                if (account.getFreezeMoney().compareTo(BigDecimal.ZERO) < 0) {
                    throw new ThrowJsonException("商家账户冻结金额不足");
                }
                boolean b = ibAccountService.updateByBid(account);
                if (!b) {
                    throw new ThrowJsonException("商家冻结账户重复提交");
                }
                d.setStatus(dto.getStatus());
                b = ibFreezeMoneyDetailService.updateById(d);
                if (!b) {
                    throw new ThrowJsonException("保存商家冻结金额的退款记录失败");
                }
            }
        }
        return "";
    }

    @Override
    public String handleFreezeAgentMoney(FreezeDTO dto) {

        if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.FREEZING.getId())) {
            AgAccount account = iAgAccountService.selectByAgid(dto.getAgid());
            BigDecimal freezeVal = account.getFreezeMoney();
            account.setFreezeMoney(CalcuUtils.getInstance().add(freezeVal, dto.getFreeze(), 2));
            boolean b = iAgAccountService.updateByAgid(account);
            if (!b) {
                throw new ThrowJsonException("重复提交");
            }
            AgFreezeMoneyDetail detail = new AgFreezeMoneyDetail();
            BeanUtils.copyProperties(dto, detail);
            detail.setMoney(dto.getFreeze());
            if (StringUtils.isBlank(dto.getRemark())) {
                detail.setRemark(HandleTypeEnums.getName(dto.getTypeId()));
            } else {
                detail.setRemark(dto.getRemark());
            }
            if (!iAgFreezeMoneyDetailService.save(detail)) {
                throw new ThrowJsonException("保存代理冻结金额记录失败");
            }
        } else if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.SEND.getId())) {
            QueryWrapper<AgFreezeMoneyDetail> queryWrapper = new QueryWrapper<>();
            //解冻粒度 批量和单个详情
            if (CalcuUtils.getInstance().isEquals(dto.getGranularity(), 2)) {
                queryWrapper.eq("order_detail_id", dto.getOrderDetailId());
            } else {
                queryWrapper.eq("pay_code", dto.getPayCode());
            }
            queryWrapper.eq("status", FreezeStatusEnums.FREEZING.getId());
            List<AgFreezeMoneyDetail> list = iAgFreezeMoneyDetailService.list(queryWrapper);
            for (AgFreezeMoneyDetail d : list) {
                if (d.getStatus() != FreezeStatusEnums.FREEZING.getId()) {
                    continue;
                }
                AgAccount account = iAgAccountService.selectByAgid(d.getAgid());
                BigDecimal freezeVal = account.getFreezeMoney();
                account.setFreezeMoney(CalcuUtils.getInstance().sub(freezeVal, d.getMoney(), 2));
                if (account.getFreezeDonate().compareTo(BigDecimal.ZERO) < 0) {
                    continue;
                }
                boolean b = iAgAccountService.updateByAgid(account);
                if (!b) {
                    continue;//重复提交
                }
                d.setStatus(dto.getStatus());
                iAgFreezeMoneyDetailService.updateById(d);
                //增加账户对应值
                insertAgMoneyDetail(d.getAgid(), d.getTypeId(), StaticUtils.PAY_IN, d.getPayCode(), d.getMoney(), d.getRemark(), d.getTargetId());
            }
        } else if (CalcuUtils.getInstance().isEquals(dto.getStatus(), FreezeStatusEnums.RETURN.getId())) {
            QueryWrapper<AgFreezeMoneyDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_detail_id", dto.getOrderDetailId());
            queryWrapper.eq("status", FreezeStatusEnums.FREEZING.getId());
            List<AgFreezeMoneyDetail> list = iAgFreezeMoneyDetailService.list(queryWrapper);
            for (AgFreezeMoneyDetail d : list) {
                if (!CalcuUtils.getInstance().isEquals(d.getStatus(), FreezeStatusEnums.FREEZING.getId())) {
                    continue;
                }
                AgAccount account = iAgAccountService.selectByAgid(d.getAgid());
                BigDecimal freezeVal = account.getFreezeMoney();
                account.setFreezeDonate(CalcuUtils.getInstance().sub(freezeVal, d.getMoney(), 2));
                if (account.getFreezeDonate().compareTo(BigDecimal.ZERO) < 0) {
                    continue;
                }
                boolean b = iAgAccountService.updateByAgid(account);
                if (!b) {
                    continue;//重复提交
                }
                d.setStatus(dto.getStatus());
                iAgFreezeMoneyDetailService.updateById(d);
            }
        }
        return "";
    }

}
